package zhieasy.cn.xpu_helper.core.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;
import zhieasy.cn.xpu_helper.security.detailservice.WechatDetailsService;
import zhieasy.cn.xpu_helper.security.filter.WeChatAuthenticationFilter;
import zhieasy.cn.xpu_helper.security.handler.*;
import zhieasy.cn.xpu_helper.security.provider.WechatAuthenticationProvider;

/**
 * @author DaHang
 * @date 2020/8/14 16:37
 */
@Component
public class WeChatSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private WechatDetailsService wechatDetailsService;
    @Autowired
    private LoginFailureHandler loginFailureHandler;
    @Autowired
    private LoginSuccessHandler loginSuccessHandler;
    @Override
    public void configure(HttpSecurity http) throws Exception {
        WeChatAuthenticationFilter weChatAuthenticationFilter = new WeChatAuthenticationFilter();
        weChatAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));

        //配置weChatAuthenticationFilter成功和失败的处理器
        weChatAuthenticationFilter.setAuthenticationSuccessHandler(loginSuccessHandler);
        weChatAuthenticationFilter.setAuthenticationFailureHandler(loginFailureHandler);

        //设置WechatAuthenticationProvider的UserDetailsService
        WechatAuthenticationProvider wechatAuthenticationProvider = new WechatAuthenticationProvider();
        wechatAuthenticationProvider.setUserDetailsService(wechatDetailsService);

        //把smsCodeAuthenticationFilter过滤器添加在UsernamePasswordAuthenticationFilter之前
        http.authenticationProvider(wechatAuthenticationProvider);
        http.addFilterBefore(weChatAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
